﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.CommonFilter;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;

namespace WSDZ.KM.ZH.CustLevelGetAndUpdate1
{
    [Description("客户等级评定获取与更新"), HotUpdate]
    public class CustLevelGetAndUpdate : AbstractDynamicFormPlugIn
    {
        public string btype = "客户等级评定获取与更新";
        public string entyKey = "FEntity";
        public string currentFormId = string.Empty;
        public override void AfterBindData(EventArgs e)
        {
            base.AfterBindData(e);
            currentFormId = View.BillBusinessInfo.GetForm().Id;
        }
        public override void ButtonClick(ButtonClickEventArgs e)
        {
            base.ButtonClick(e);
            //获取客户信息
            if (e.Key.EqualsV1("F_RLKX_Buttonhq"))
            {
                try
                {
                    string d1 = Model.GetValue("F_RLKX_SDate").ToStringV1();
                    string d2 = Model.GetValue("F_RLKX_EDate").ToStringV1();
                    int orgId = 0;
                    if (d1.IsNullOrEmptyOrWhiteSpace()|| d2.IsNullOrEmptyOrWhiteSpace())
                    {
                        View.ShowErrMessage("统计日期不可空!!!");
                        return;
                    }
                    DynamicObject orgObj = Model.GetValue("F_RLKX_ORGID") as DynamicObject;
                    if (orgObj!=null)
                        orgId = orgObj["Id"].ToStringV1().ToInt32V1();
                    if (orgId==0)
                    {
                        View.ShowErrMessage("组织不可为空!!!");
                        return;
                    }
                    Model.DeleteEntryData(entyKey);

                    string date1 = d1.ToDateTime().ToString("yyyy-MM-dd");
                    string date2 = d2.ToDateTime().ToString("yyyy-MM-dd 23:59:59");
                    //                    string sql = $@"/*dialect*/ select 
                    //custId=cust.FCUSTID
                    //,custNumber=cust.FNUMBER
                    //,custLevel=cust.F_RLKX_KHDJ
                    //,amount=SUM(entyF.FALLAMOUNT_LC)
                    //from T_SAL_ORDERENTRY enty
                    //left join T_SAL_ORDERENTRY_F entyF on enty.FEntryId=entyF.FEntryId
                    //left join T_SAL_ORDER main on enty.FID=main.FID
                    //left join T_BD_CUSTOMER cust on main.FCUSTID=cust.FCUSTID
                    //where main.FDOCUMENTSTATUS='C'
                    //and enty.FMANUALROWCLOSE=0
                    //and main.FSALEORGID={orgId}
                    //and main.FDATE>='{date1}'
                    //and main.FDATE<='{date2}'
                    //and cust.FDOCUMENTSTATUS='C'
                    //and cust.FFORBIDSTATUS='A'
                    //group by cust.FCUSTID,cust.FNUMBER,cust.F_RLKX_KHDJ";
                    string sql = $@"/*dialect*/ select 
custId=cust.FCUSTID
,custNumber=cust.FNUMBER
,custLevel=cust.F_RLKX_KHDJ
,amount=salInfo.amount
from T_BD_CUSTOMER cust
left join 
(select 
custId=salCust.FCUSTID
,amount=SUM(entyF.FALLAMOUNT_LC)
from T_SAL_ORDERENTRY enty
left join T_SAL_ORDERENTRY_F entyF on enty.FEntryId=entyF.FEntryId
left join T_SAL_ORDER main on enty.FID=main.FID
left join T_BD_CUSTOMER salCust on main.FCUSTID=salCust.FCUSTID
where main.FDOCUMENTSTATUS='C'
and enty.FMANUALROWCLOSE=0
and main.FSALEORGID={orgId}
and main.FDATE>='{date1}'
and main.FDATE<='{date2}'
and salCust.FDOCUMENTSTATUS='C'
and salCust.FFORBIDSTATUS='A'
group by salCust.FCUSTID
)salInfo on cust.FCUSTID=salInfo.custId
where cust.FDOCUMENTSTATUS='C'
and cust.FFORBIDSTATUS='A'";
                    DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(Context,sql);
                    if (datas==null||datas.Count<1)
                        return;
                    List<CustInfo> custList = datas.DynamicObjectCollectionToDataList<CustInfo>();
                    FillEntry(custList);
                }
                catch (Exception ex)
                {
                    View.ShowErrMessage(ex.Message);
                }
            }
            //更新客户等级
            else if (e.Key.EqualsV1("F_RLKX_Buttongx"))
            {
                try
                {
                    int orgId = 0;
                    DynamicObject orgObj = Model.GetValue("F_RLKX_ORGID") as DynamicObject;
                    if (orgObj != null)
                        orgId = orgObj["Id"].ToStringV1().ToInt32V1();
                    if (orgId == 0)
                    {
                        View.ShowErrMessage("组织不可为空!!!");
                        return;
                    }
                    Entity entity = this.Model.BillBusinessInfo.GetEntity(entyKey);
                    DynamicObjectCollection rows = this.Model.GetEntityDataObject(entity);
                    if (rows==null)
                        return;
                    var uList = rows.Where(x=>!x["F_RLKX_updatems"].ToStringV1().EqualsV1("更新成功")).Select(x =>  {
                        int seq = x["Seq"].ToStringV1().ToInt32V1();
                        DynamicObject custObj = x["F_RLKX_custno"] as DynamicObject;
                        int custId = custObj == null ? 0 : custObj["Id"].ToStringV1().ToInt32V1();
                        DynamicObject levelObj = x["F_RLKX_gxhkhdj"] as DynamicObject;
                        int custLevelId = levelObj == null ? 0 : levelObj["Id"].ToStringV1().ToInt32V1();
                        string levelType = x["F_RLKX_djgxlx"].ToStringV1();
                        return new
                        {
                            seq = seq,
                            custId = custId,
                            custLevelId = custLevelId,
                            levelType = levelType,
                        };  
                    }).ToList();
                    if (uList!=null&&uList.Count>0)
                    {
                        foreach (var uobj in uList)
                        {
                            string sql_u = $@"/*dialect*/ update T_BD_CUSTOMER set F_RLKX_KHDJ={uobj.custLevelId},F_RLKX_DJGXLX='{uobj.levelType}' 
                            where FCUSTID={uobj.custId} and FUSEORGID={orgId}";
                            int i = DBUtils.Execute(Context,sql_u);
                            if (i>0)
                            {
                                Model.SetValue("F_RLKX_updatems","更新成功",uobj.seq-1);
                            }
                            else
                            {
                                Model.SetValue("F_RLKX_updatems", "更新失败", uobj.seq-1);
                            }
                        }
                        View.UpdateView(entyKey);
                    }

                }
                catch (Exception ex)
                {
                    View.ShowErrMessage(ex.Message);
                }
            }
        }
        public void FillEntry(List<CustInfo> custList)
        {
            if (custList == null || custList.Count < 1)
                return;
            List<CustLevel> leList = new List<CustLevel>();
            string sql = $@"select 
Id=FID
,amount1= F_RLKX_ZDJE
,amount2= F_RLKX_ZGJE
from T_BAS_PREBDFIVE 
where fdocumentstatus='C' 
and ISNULL(FFORBIDSTATUS,'A')='A'";
            DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(Context, sql);
            if (datas!=null)
                leList = datas.DynamicObjectCollectionToDataList<CustLevel>();
            Entity entity = this.Model.BillBusinessInfo.GetEntity(entyKey);
            DynamicObjectCollection rows = this.Model.GetEntityDataObject(entity);
            int seq = 1;
            foreach (var data in custList)
            {
                DynamicObject row = new DynamicObject(entity.DynamicObjectType);
                entity.SeqDynamicProperty.SetValue(row, seq);
                DynamicObject custObj = UtilityManager.GetDynamicObjectById(Context,currentFormId, "F_RLKX_custno",data.custId);
                if (custObj!=null)
                {
                    row["F_RLKX_custno_Id"] = data.custId;
                    row["F_RLKX_custno"] = custObj;
                    //View.InvokeFieldUpdateService("F_RLKX_custno",seq);
                    DynamicObject currentLevel = UtilityManager.GetDynamicObjectById(Context, currentFormId, "F_RLKX_khgrade", data.custLevel);
                    if (currentLevel != null)
                    {
                        row["F_RLKX_khgrade_Id"] = data.custLevel;
                        row["F_RLKX_khgrade"] = currentLevel;
                    }
                }
                row["F_RLKX_Amount"] = data.amount;
                row["F_RLKX_djgxlx"] = "系统";
                CustLevel levelObj = leList.Where(x => data.amount >= x.amount1 && data.amount <= x.amount2).FirstOrDefault();
                if (levelObj != null)
                {
                    int levelId = levelObj.Id;
                    DynamicObject leveldata = UtilityManager.GetDynamicObjectById(Context, currentFormId, "F_RLKX_gxhkhdj", levelId);
                    if (leveldata!=null)
                    {
                        row["F_RLKX_gxhkhdj_Id"] = levelId;
                        row["F_RLKX_gxhkhdj"] = leveldata;
                        //View.InvokeFieldUpdateService("F_RLKX_gxhkhdj", seq);
                    }
                }
                
                rows.Add(row);
                seq++;
            }
            View.UpdateView(entyKey);
        }
    }
    public class CustInfo
    {
        public int custId { get; set; }
        public string custNumber { get; set; }
        public int custLevel { get; set; }
        public decimal amount { get; set; }
    }
    public class CustLevel
    {
        public int Id { get; set; }
        public decimal amount1 { get; set; }
        public decimal amount2 { get; set; }
    }
}
